package com.qunar.wan.web.controller.common;

import org.springframework.http.HttpStatus;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * User: cyoung Date: 11/25/13 Time: 11:20 AM
 */
public abstract class AbstractController extends ExceptionJsonController {

    private final String LOCAL_IP = getLocalIP();

    /**
     * 请求处理成功返回Json数据
     * 
     * @param data
     * @param responseTime 接口响应时间 ms
     * @return
     */
    protected DataMap dataJson(Object data, long responseTime) {
        DataMap map = new DataMap();
        map.put("SERVER_IP", LOCAL_IP);
        map.put("RESPONSE_TIME", responseTime + "ms");
        map.put("ret", true);
        map.put("data", data);
        return map;
    }

    /**
     * 请求处理失败返回Json数据
     * 
     * @param errcode 可以自定义code
     * @return
     */
    protected DataMap errorJson(int errcode, String errmsg) {
        DataMap map = new DataMap();
        map.put("SERVER_IP", LOCAL_IP);
        map.put("ret", false);
        map.put("errcode", errcode);
        map.put("errmsg", errmsg);
        return map;
    }

    /**
     * 请求处理失败返回Json数据
     * 
     * @param errcode 可以自定义code
     * @return
     */
    protected DataMap errorJson(int errcode, String errmsg, long responseTime) {
        DataMap map = new DataMap();
        map.put("SERVER_IP", LOCAL_IP);
        map.put("RESPONSE_TIME", responseTime + "ms");
        map.put("ret", false);
        map.put("errcode", errcode);
        map.put("errmsg", errmsg);
        return map;
    }

    /**
     * 请求处理失败返回Json数据
     * 
     * @param errcode HttpStatu
     * @return
     */
    protected DataMap errorJson(HttpStatus errcode, String errmsg, long responseTime) {
        DataMap map = new DataMap();
        map.put("SERVER_IP", LOCAL_IP);
        map.put("RESPONSE_TIME", responseTime + "ms");
        map.put("ret", false);
        map.put("errcode", errcode);
        map.put("errmsg", errmsg);
        return map;
    }

    /**
     * 获取本机IP地址
     * 
     * @return String
     */
    private String getLocalIP() {
        InetAddress ip = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("获取本地IP异常{}", e);
        }
        return "UNKNOWN";
    }
}
